package com.fly.show.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.IntStream;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.fly.show.model.User;
import com.fly.show.service.IUserService;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserService implements IUserService
{
    private List<User> users = Lists.newArrayList();
    
    private Long sequence = 0L;
    
    /**
     * 初始化
     * 
     * @see [类、类#方法、类#成员]
     */
    @PostConstruct
    public void init()
    {
        IntStream.range(0, 5).forEach(i -> {
            users.add(new User().setUserId(++sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence).setCreateTime(new Date()));
        });
    }
    
    private void insert(User user)
    {
        log.info("insert user : {}", user);
        users.add(user.setUserId(++sequence));
    }
    
    private void update(User user)
    {
        log.info("update user id = {}", user.getUserId());
        for (User it : users)
        {
            if (it.getUserId().equals(user.getUserId()))
            {
                it.setUserName(user.getUserName()).setAge(user.getAge()).setDesc(user.getDesc());
                return;
            }
        }
    }
    
    /**
     * 新增/根据id更新
     * 
     * @param user
     * @see [类、类#方法、类#成员]
     */
    @Override
    @Caching(evict = {@CacheEvict(value = "users", key = "#user.userId"), @CacheEvict(value = "users", allEntries = true)})
    public void saveOrUpdate(User user)
    {
        if (user.getUserId() != null)
        {
            update(user);
            return;
        }
        insert(user);
    }
    
    @Override
    @Caching(evict = {@CacheEvict(value = "users", key = "#userId"), @CacheEvict(value = "users", allEntries = true)})
    public void delete(Long userId)
    {
        log.info("delete user id = {}", userId);
        for (User user : users)
        {
            if (user.getUserId().equals(userId))
            {
                users.remove(user);
                return;
            }
        }
    }
    
    @Override
    @Cacheable(value = "users", key = "#userId", unless = "#result==null")
    public User get(Long userId)
    {
        log.info("get user id = {}", userId);
        for (User user : users)
        {
            if (user.getUserId().equals(userId))
            {
                return user;
            }
        }
        return null;
    }
    
    @Override
    @Cacheable("users")
    public List<User> list()
    {
        log.info("list users");
        return users;
    }
}
